// 全局任务列表
let tasks = new Map();

// 选择目录
async function selectDirectory(type) {
    try {
        const response = await fetch(`/select_directory?type=${type}`);
        const data = await response.json();
        if (response.ok) {
            const input = document.getElementById(`${type}Dir`);
            input.value = data.path;
            
            if (type === 'input') {
                updateInputStats(data.stats);
            }
        } else {
            alert(data.error);
        }
    } catch (error) {
        console.error('选择目录失败:', error);
        alert('选择目录失败');
    }
}

// 更新输入目录统计信息
function updateInputStats(stats) {
    const statsDiv = document.getElementById('inputStats');
    statsDiv.innerHTML = `
        <small class="text-muted">
            共 ${stats.total_files} 个文件，
            总大小: ${formatSize(stats.total_size)}，
            平均大小: ${formatSize(stats.average_size)}
        </small>
    `;
}

// 格式化文件大小
function formatSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 创建任务卡片
function createTaskCard(taskId) {
    const template = document.getElementById('taskTemplate');
    const card = template.content.cloneNode(true);
    
    card.querySelector('.task-id').textContent = taskId;
    card.querySelector('.task-card').id = `task-${taskId}`;
    
    document.getElementById('taskList').prepend(card);
    return document.getElementById(`task-${taskId}`);
}

// 更新任务状态
function updateTaskCard(taskId, data) {
    const card = document.getElementById(`task-${taskId}`);
    if (!card) return;
    
    const statusBadge = card.querySelector('.task-status');
    const progressBar = card.querySelector('.progress-bar');
    const progressText = card.querySelector('.task-progress');
    const durationText = card.querySelector('.task-duration');
    const passRateText = card.querySelector('.task-pass-rate');
    
    // 更新状态标签
    statusBadge.textContent = getStatusText(data.status);
    statusBadge.className = `badge ${getStatusClass(data.status)}`;
    
    // 更新进度
    const progress = (data.progress * 100).toFixed(1);
    progressBar.style.width = `${progress}%`;
    progressBar.textContent = `${progress}%`;
    
    // 更新处理进度
    progressText.textContent = `${data.processed_files}/${data.total_files}`;
    
    // 更新持续时间
    durationText.textContent = formatDuration(data.duration);
    
    // 更新通过率
    const passedCount = Object.values(data.results).filter(r => r.status === 'success').length;
    const passRate = data.total_files > 0 ? (passedCount / data.total_files * 100).toFixed(1) : 0;
    passRateText.textContent = `${passRate}%`;
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': '等待中',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '失败'
    };
    return statusMap[status] || status;
}

// 获取状态样式类
function getStatusClass(status) {
    const classMap = {
        'pending': 'bg-secondary',
        'processing': 'bg-primary',
        'completed': 'bg-success',
        'failed': 'bg-danger'
    };
    return classMap[status] || 'bg-secondary';
}

// 格式化持续时间
function formatDuration(seconds) {
    if (seconds < 60) return `${Math.round(seconds)}秒`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.round(seconds % 60);
    return `${minutes}分${remainingSeconds}秒`;
}

// 查看结果
function viewResults(button) {
    const card = button.closest('.task-card');
    const resultsContainer = card.querySelector('.results-container');
    const isVisible = resultsContainer.style.display !== 'none';
    
    if (isVisible) {
        resultsContainer.style.display = 'none';
        button.textContent = '查看结果';
    } else {
        resultsContainer.style.display = 'block';
        button.textContent = '隐藏结果';
        updateResultsList(card.id.split('-')[1]);
    }
}

// 更新结果列表
async function updateResultsList(taskId) {
    try {
        const response = await fetch(`/task/${taskId}/results`);
        const data = await response.json();
        
        if (response.ok) {
            const card = document.getElementById(`task-${taskId}`);
            const filteredList = card.querySelector('.filtered-list');
            const passedList = card.querySelector('.passed-list');
            
            // 清空现有内容
            filteredList.innerHTML = '<div class="list-group-item active">未通过图片</div>';
            passedList.innerHTML = '<div class="list-group-item active">已通过图片</div>';
            
            // 添加未通过的图片
            Object.values(data.results).filter(r => r.status !== 'success').forEach(result => {
                const item = document.createElement('div');
                item.className = 'list-group-item';
                item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>${result.filename}</div>
                        <small class="text-muted">${result.filter_reasons.map(r => r.message).join(', ')}</small>
                    </div>
                `;
                filteredList.appendChild(item);
            });
            
            // 添加已通过的图片
            Object.values(data.results).filter(r => r.status === 'success').forEach(result => {
                const item = document.createElement('div');
                item.className = 'list-group-item';
                item.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <div>${result.filename}</div>
                        <small class="text-muted">聚类ID: ${result.analysis.cluster}</small>
                    </div>
                `;
                passedList.appendChild(item);
            });
        }
    } catch (error) {
        console.error('获取结果失败:', error);
    }
}

// 定期更新任务状态
function startTaskUpdates() {
    setInterval(async () => {
        try {
            const response = await fetch('/tasks');
            const tasks = await response.json();
            
            tasks.forEach(task => {
                updateTaskCard(task['task_id'], task);
            });

        } catch (error) {
            console.error('更新任务状态失败:', error);
        }
    }, 1000);
}

// 表单提交处理
document.getElementById('taskForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const inputDir = document.getElementById('inputDir').value;
    const outputDir = document.getElementById('outputDir').value;
    
    if (!inputDir || !outputDir) {
        alert('请选择输入和输出目录');
        return;
    }
    
    try {
        const response = await fetch('/create_task', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                input_dir: inputDir,
                output_dir: outputDir
            })
        });
        
        const data = await response.json();
        if (response.ok) {
            createTaskCard(data.task_id);
            document.getElementById('inputDir').value = '';
            document.getElementById('outputDir').value = '';
            document.getElementById('inputStats').innerHTML = '';
        } else {
            alert(data.error);
        }
    } catch (error) {
        console.error('创建任务失败:', error);
        alert('创建任务失败');
    }
});

// 启动任务状态更新
startTaskUpdates(); 